import { defineStore } from 'pinia'
import { getOrderList, getOrderDetail, createOrder, updateOrder, deleteOrder } from '@/api/order'

export const useOrderStore = defineStore('order', {
  state: () => ({
    orderList: [],
    orderDetail: {},
    loading: false,
    total: 0
  }),

  actions: {
    // 获取订单列表
    async fetchOrderList(params) {
      this.loading = true
      try {
        const response = await getOrderList(params)
        this.orderList = response.data
        this.total = response.total
        return response
      } catch (error) {
        console.error('获取订单列表失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取订单详情
    async fetchOrderDetail(id) {
      this.loading = true
      try {
        const response = await getOrderDetail(id)
        this.orderDetail = response.data
        return response
      } catch (error) {
        console.error('获取订单详情失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 创建订单
    async createOrder(data) {
      try {
        const response = await createOrder(data)
        // 如果当前在订单列表页，重新获取列表
        if (this.orderList.length > 0) {
          await this.fetchOrderList({})
        }
        return response
      } catch (error) {
        console.error('创建订单失败:', error)
        throw error
      }
    },

    // 更新订单
    async updateOrder(id, data) {
      try {
        const response = await updateOrder(id, data)
        // 更新订单列表中的数据
        const index = this.orderList.findIndex(order => order.id === id)
        if (index !== -1) {
          this.orderList[index] = { ...this.orderList[index], ...data }
        }
        // 如果是当前详情页的订单，也更新详情数据
        if (this.orderDetail.id === id) {
          this.orderDetail = { ...this.orderDetail, ...data }
        }
        return response
      } catch (error) {
        console.error('更新订单失败:', error)
        throw error
      }
    },

    // 删除订单
    async deleteOrder(id) {
      try {
        const response = await deleteOrder(id)
        // 从订单列表中移除
        this.orderList = this.orderList.filter(order => order.id !== id)
        this.total--
        return response
      } catch (error) {
        console.error('删除订单失败:', error)
        throw error
      }
    }
  }
})